//
//  ProfileInfoViewController.m
//  Health
//
//  Created by LeeJay on 16/8/29.
//  Copyright © 2016年 LeeJay. All rights reserved.
//

#import "ProfileInfoViewController.h"
#import <HealthKit/HealthKit.h>
#import "HKHealthStore+Extension.h"
#import "StepCountModel.h"
#import "NSDate+Extension.h"

@interface ProfileInfoViewController ()

@property (weak, nonatomic) IBOutlet UITextField *ageTextField;
@property (weak, nonatomic) IBOutlet UITextField *heightTextField;
@property (weak, nonatomic) IBOutlet UITextField *weightTextField;
@property (weak, nonatomic) IBOutlet UITextField *stepCountTextField;

@end

@implementation ProfileInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self updateAge];
    [self updateWeight];
    [self updateHeight];
    [self updateStepCount];
}

/**
 获取步数
 */
- (void)updateStepCount
{
    NSDate *end = [NSDate date];
    
    // 计算一天的步数
    NSDate *start = [NSDate getTodayAgoWithDays:1];
    
    [self.healthStore getStepCountStartDate:start
                                    endDate:end
                                    success:^(NSArray *results) {
                                        if (results.count) {
                                            StepCountModel *model = results.firstObject;
                                            dispatch_async(dispatch_get_main_queue(), ^{
                                                self.stepCountTextField.text = [NSString stringWithFormat:@"%zd",model.stepCount];
                                            });
                                        } else {
                                            dispatch_async(dispatch_get_main_queue(), ^{
                                                self.weightTextField.placeholder = @"Enter in step count";
                                            });
                                        }
                                        
    } failure:^(NSError *error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.weightTextField.placeholder = @"Enter in step count";
        });
    }];
}

/**
 获取年龄
 */
- (void)updateAge
{
    NSError *error = nil;
    NSDate *dateOfBirth = [self.healthStore dateOfBirthWithError:&error];
    
    if (!dateOfBirth) {
        NSLog(@"No age was found");
        
        dispatch_async(dispatch_get_main_queue(), ^{
           self.ageTextField.placeholder = @"Enter in HealthKit App";
        });
        
    } else {
        NSDate *now = [NSDate date];
        NSDateComponents *ageComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitYear fromDate:dateOfBirth toDate:now options:NSCalendarWrapComponents];
        NSInteger userAge = [ageComponents year];
        self.ageTextField.text = [NSNumberFormatter localizedStringFromNumber:@(userAge) numberStyle:NSNumberFormatterNoStyle];
    }
}

/**
 获取体重
 */
- (void)updateWeight
{
    HKQuantityType *weightType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
    
    [self.healthStore mostRecentQuantitySampleOfType:weightType predicate:nil completion:^(HKQuantity *mostRecentQuantity, NSError *error) {
        if (!mostRecentQuantity) {
            NSLog(@"No weight was found");
            dispatch_async(dispatch_get_main_queue(), ^{
               self.weightTextField.placeholder = @"Enter in weight";
            });
        } else {
            HKUnit *weightUnit = [HKUnit gramUnitWithMetricPrefix:HKMetricPrefixKilo];
            double usersWeight = [mostRecentQuantity doubleValueForUnit:weightUnit];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.weightTextField.text = [NSNumberFormatter localizedStringFromNumber:@(usersWeight) numberStyle:NSNumberFormatterNoStyle];
            });
        }
    }];
}

/**
 获取身高
 */
- (void)updateHeight
{
    HKQuantityType *heightType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];
    
    [self.healthStore mostRecentQuantitySampleOfType:heightType predicate:nil completion:^(HKQuantity *mostRecentQuantity, NSError *error) {
        if (!mostRecentQuantity) {
            NSLog(@"No Height was found");
            dispatch_async(dispatch_get_main_queue(), ^{
                self.heightTextField.placeholder = @"Enter in height";
            });
        } else {
            double usersHeight = [mostRecentQuantity doubleValueForUnit:[HKUnit meterUnit]];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.heightTextField.text = [NSString stringWithFormat:@"%.2f",usersHeight];
            });
        }
    }];
}

/**
 保存体重
 
 @param height 体重
 */
- (void)saveWeightIntoHealthStore:(double)weight
{
    HKUnit *weightUnit = [HKUnit gramUnitWithMetricPrefix:HKMetricPrefixKilo];
    HKQuantity *weightQuantity = [HKQuantity quantityWithUnit:weightUnit doubleValue:weight];
    
    HKQuantityType *weightType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
    
    NSDate *now = [NSDate date];
    
    HKQuantitySample *weightSample = [HKQuantitySample quantitySampleWithType:weightType quantity:weightQuantity startDate:now endDate:now];
    
    [self.healthStore saveObject:weightSample withCompletion:^(BOOL success, NSError * _Nullable error) {
        if (!success) {
            NSLog(@"%@",error);
        } else {
            NSLog(@"%@",@"保存成功");
        }
        [self updateWeight];
    }];
}

/**
 保存身高
 
 @param weight 身高
 */
- (void)saveHeightIntoHealthStore:(double)height
{
    HKUnit *heightUnit = [HKUnit meterUnit];
    HKQuantity *heightQuantity = [HKQuantity quantityWithUnit:heightUnit doubleValue:height];
    
    HKQuantityType *heightType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];
    
    NSDate *now = [NSDate date];
    
    HKQuantitySample *weightSample = [HKQuantitySample quantitySampleWithType:heightType quantity:heightQuantity startDate:now endDate:now];
    
    [self.healthStore saveObject:weightSample withCompletion:^(BOOL success, NSError * _Nullable error) {
        if (!success) {
            NSLog(@"%@",error);
        } else {
            NSLog(@"%@",@"保存成功");
        }
        [self updateHeight];
    }];
}

/**
 保存步数
 
 @param stepCount 步数
 */
- (void)saveStepCountIntoHealthStore:(double)stepCount
{
    HKUnit *stepCountUnit = [HKUnit countUnit];
    HKQuantity *stepCountQuantity = [HKQuantity quantityWithUnit:stepCountUnit doubleValue:stepCount];
    
    HKQuantityType *stepCountType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    
    NSDate *now = [NSDate date];
    
    HKQuantitySample *stepCountSample = [HKQuantitySample quantitySampleWithType:stepCountType quantity:stepCountQuantity startDate:now endDate:now];
    
    [self.healthStore saveObject:stepCountSample withCompletion:^(BOOL success, NSError * _Nullable error) {
        if (!success) {
            NSLog(@"%@",error);
        } else {
            NSLog(@"%@",@"保存成功");
        }
        [self updateStepCount];
    }];
}

- (IBAction)saveBtnClick:(id)sender
{
    [self saveHeightIntoHealthStore:[_heightTextField.text doubleValue]];
    [self saveWeightIntoHealthStore:[_weightTextField.text doubleValue]];
    [self saveStepCountIntoHealthStore:[_stepCountTextField.text doubleValue]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
